package com.hospital.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hospital.configure.Result;
import com.hospital.entity.FeeRecord;
import com.hospital.entity.Registered;
import com.hospital.entity.Registered;
import com.hospital.entity.User;
import com.hospital.mapper.FeeRecordMapper;
import com.hospital.mapper.RegisteredMapper;
import com.hospital.mapper.RegisteredMapper;
import com.hospital.mapper.UserMapper;
import com.hospital.service.RegisteredService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hospital.utils.IDGenerator;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author WuLiTing
 * @since 2021-03-28
 */
@Service
public class RegisteredServiceImpl extends ServiceImpl<RegisteredMapper, Registered> implements RegisteredService {

    @Resource
    RegisteredMapper registeredMapper;

    @Resource
    UserMapper userMapper;

    @Resource
    FeeRecordMapper feeRecordMapper;

    @Override
    public Result<Registered> updateRegistered(Registered registered) {
        Result<Registered> result = new Result<>();
        try {
            if (StringUtils.isEmpty(registered.getRegisteredId())) {
                //如果ID为空，代表添加
                registered.setRegisteredId(IDGenerator.getUUID("REGISTERED"));
                registeredMapper.insert(registered);
            } else {
                //如果ID不为空，代表修改
                registeredMapper.updateById(registered);
            }
            result.setMessage("success");
        } catch (Exception e) {
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @Override
    public Result<Registered> delRegistered(Registered registered) {
        Result<Registered> result = new Result<>();
        try {
            if (StringUtils.isEmpty(registered.getRegisteredId())) {
                result.setMessage("registeredId can't be empty");
                return result;
            }
            registeredMapper.deleteById(registered.getRegisteredId());
            result.setMessage("success");
        } catch (Exception e) {
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @Override
    public Result<Registered> batchDelRegistered(Registered registered) {
        Result<Registered> result = new Result<>();
        try {
            if (!StringUtils.isEmpty(registered.getIds())) {
                String[] ids = registered.getIds().split(",");
                for (String id : ids) {
                    registeredMapper.deleteById(id);
                }
            }
        } catch (Exception e) {
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @Override
    public Result<Registered> queryRegistered(Registered registered) {
        Result<Registered> result = new Result<>();
        try {
            QueryWrapper<Registered> wrapper = new QueryWrapper<>();
            //查询条件拼接，仅限单表查询可用

            List<Registered> registereds = registeredMapper.selectList(wrapper);
            result.setReturnList(registereds);
            result.setMessage("success");
        } catch (Exception e) {
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @Override
    public Result<Registered> queryRegisteredByPage(Registered registered) {
        Result<Registered> result = new Result<>();

        try {
            if (registered.getCurrent() == null || registered.getSize() == null) {
                result.setMessage("current or size can't be null");
                return result;
            }

            IPage<Registered> registereds = registeredMapper.queryRegisteredByPage(new Page<>(registered.getCurrent(), registered.getSize()), registered);
            result.setReturnPage(registereds);
            result.setMessage("success");
        } catch (Exception e) {
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @Override
    public Result<Registered> queryRegisteredById(Registered registered) {
        Result<Registered> result = new Result<>();
        try {
            Registered returnRegistered = registeredMapper.selectById(registered.getRegisteredId());
            result.setReturnObj(returnRegistered);
            result.setMessage("success");
        } catch (Exception e) {
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @Override
    public Result<Map> queryRegisteredList(Map map) {
        Result<Map> result = new Result<>();
        try {
            Page<Map> pageList = registeredMapper.queryRegisteredList(new Page((int) map.get("current"), (int) map.get("size")), map);
            result.setReturnPage(pageList);
            result.setMessage("success");
        } catch (Exception e) {
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @Override
    public Result<Registered> addRegistered(Map map) {
        Result<Registered> result = new Result<>();
        try {
            Registered registered = new Registered();
            registered.setRegisteredId(IDGenerator.getUUID("REGISTERED"));
            registered.setDoctorId(map.get("doctorId").toString());
            registered.setRegisteredDate(map.containsKey("registeredDate") ? new SimpleDateFormat("yyyy-MM-dd").parse(map.get("registeredDate").toString()) : new Date());
            System.out.println(registered.getRegisteredDate().toLocaleString());
            registered.setSort(registeredMapper.queryRegisteredCount(map.get("doctorId").toString(), registered.getRegisteredDate()));
            registered.setCreateTime(new Date());
            registered.setCreateUser(map.get("createUser").toString());
            registered.setRegisteredStatus("0");

            if (map.containsKey("userId") && map.get("userId") != null) {
                registered.setUserId(map.get("userId").toString());
            } else {
                User user = new User();
                user.setUserId(IDGenerator.getUUID("USER"));
                user.setUserType("3");
                user.setUserStatus("0");
                user.setUserName(map.get("userName").toString());
                user.setUserAccount(map.get("phoneNumber").toString());
                user.setUserPassword("123456");
                user.setSex(map.get("sex").toString());
                user.setAge(Integer.parseInt(map.get("age").toString()));
                user.setPhoneNumber(map.get("phoneNumber").toString());
                user.setIdentity(map.get("identity").toString());
                user.setCreateTime(new Date());

                userMapper.insert(user);

                registered.setUserId(user.getUserId());
            }
            registeredMapper.insert(registered);
            result.setReturnObj(registered);
            result.setMessage("success");
        } catch (Exception e) {
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @Override
    public Result registeredPay(Registered registered) {
        Result result = new Result<>();
        try {
            //更新付款状态
            registeredMapper.updateStatus(registered);

            //添加挂号费用记录：姓名，付款类别，付款数，收款人，收款时间，支付宝账单，备注
            FeeRecord feeRecord = new FeeRecord();
            Registered registeredRecord = registeredMapper.selectById(registered.getRegisteredId());
            feeRecord.setUserId(registeredRecord.getUserId());
            feeRecord.setUserName(userMapper.selectById(registeredRecord.getUserId()).getUserName());
            feeRecord.setFeeType("挂号费用");
            feeRecord.setCreateUser(registeredRecord.getCreateUser());
            feeRecord.setCreateUserName(userMapper.selectById(registeredRecord.getCreateUser()).getUserName());
            feeRecord.setRecordId(IDGenerator.getUUID("FEERECORD"));
            feeRecord.setFeeAmount(registered.getRegisteredFee());
            feeRecord.setCreateTime(new Date());
            feeRecord.setTradeNo("线下支付");
            feeRecord.setOrderId(registered.getRegisteredId());
            feeRecord.setRemark("线下支付");
            feeRecordMapper.insert(feeRecord);
            result.setMessage("success");
        } catch (Exception e) {
            result.setMessage(e.getMessage());
        }
        return result;
    }

}
